package cn.tedu.luban.worker.main.service;

import cn.tedu.luban.account.api.AccountApi;
import cn.tedu.luban.account.protocol.param.AccountCreateParam;
import cn.tedu.luban.attach.api.AttachApi;
import cn.tedu.luban.attach.protocol.dto.AttachDTO;
import cn.tedu.luban.attach.protocol.query.AttachQuery;
import cn.tedu.luban.worker.common.enums.WorkerResultEnum;
import cn.tedu.luban.worker.main.converter.WorkerConverter;
import cn.tedu.luban.worker.main.repository.WorkerAreaRepository;
import cn.tedu.luban.worker.main.repository.WorkerAuditRepository;
import cn.tedu.luban.worker.main.repository.WorkerCategoryRepository;
import cn.tedu.luban.worker.main.repository.WorkerRepository;
import cn.tedu.luban.worker.protocol.bo.AdminAuditBO;
import cn.tedu.luban.worker.protocol.bo.WorkerAreaBO;
import cn.tedu.luban.worker.protocol.bo.AdminWorkerBO;
import cn.tedu.luban.worker.protocol.bo.WorkerCategoryBO;
import cn.tedu.luban.worker.protocol.param.AuditSubmitParam;
import cn.tedu.luban.worker.protocol.param.WorkerParam;
import cn.tedu.luban.worker.protocol.query.WorkerListQuery;
import com.tedu.inn.protocol.ListRecordTotalBO;
import com.tedu.inn.protocol.exception.BusinessException;
import java.util.ArrayList;
import java.util.List;
import org.checkerframework.checker.units.qual.A;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

@Service
public class WorkerAdminService {
    @Autowired
    private WorkerRepository workerRepository;
    @Autowired
    private WorkerCategoryRepository workerCategoryRepository;
    @Autowired
    private WorkerAreaRepository workerAreaRepository;
    @Autowired
    private WorkerAuditRepository workerAuditRepository;
    @Autowired(required = false)
    private AttachApi attachApi;
    @Autowired
    private WorkerConverter workerConverter;
    public ListRecordTotalBO<AdminWorkerBO> workerAuditList(WorkerListQuery query) {
        // 准备一个返回值
        ListRecordTotalBO<AdminWorkerBO> workerBOList=null;
        if (CollectionUtils.isEmpty(query.getAuditStatus())){
            List<Integer> auditStatus = new ArrayList<>();
            auditStatus.add(0);
            auditStatus.add(2);
            query.setAuditStatus(auditStatus);
        }
        // 查询总数 条件workerQuery非空 auditStatus
        Long total=workerRepository.countWorker(query);
        if (total==0){
            //返回
            workerBOList=new ListRecordTotalBO<>(null,total);
        }else{
            //查询 具体分页数据
            List<AdminWorkerBO> adminWorkerBOS = workerRepository.queryWorkers(query);
            //封装 area工作区域 和category工作品类
            replenish(adminWorkerBOS);
            workerBOList=new ListRecordTotalBO<>(adminWorkerBOS,total);
        }
        return workerBOList;
    }

    private void replenish(List<AdminWorkerBO> bos) {
        if (!CollectionUtils.isEmpty(bos)){
            for (AdminWorkerBO bo : bos) {
                Long userId=bo.getUserId();
                List<String> areaDetails=new ArrayList<>();
                List<String> categoryDetails=new ArrayList<>();
                List<WorkerAreaBO> areas=workerAreaRepository.getWorkerAreas(userId);
                List<WorkerCategoryBO> categories=workerCategoryRepository.getWorkerCategories(userId);
                for (WorkerCategoryBO category : categories) {
                    String categoryDetail=category.getCategoryDetail();
                    categoryDetails.add(categoryDetail);
                }
                for (WorkerAreaBO area : areas) {
                    String areaDetail=area.getAreaDetail();
                    areaDetails.add(areaDetail);
                }
                bo.setAreaDetails(areaDetails);
                bo.setCategoryDetails(categoryDetails);
            }
        }
    }
    private void replenish(AdminWorkerBO bo) {
        List<AdminWorkerBO> adminWorkerBOS =new ArrayList<>();
        adminWorkerBOS.add(bo);
        replenish(adminWorkerBOS);
    }

    public AdminWorkerBO auditDetail(Long userId) throws BusinessException {
        AdminWorkerBO adminWorkerBO = workerRepository.getWorker(userId);
        if (adminWorkerBO ==null|| adminWorkerBO.getId()==null){
            //前端传递的userId没有查询到worker
            throw new BusinessException(WorkerResultEnum.WORKER_NOT_FOUND);
        }else {
            //3.封装area区域,封装category品类
            replenish(adminWorkerBO);
            //5.封装历史审核记录
            List<AdminAuditBO> audit = workerAuditRepository.getWorkerAuditLogs(userId);
            adminWorkerBO.setWorkerAuditLogs(audit);
            //6.rpc调用查询图片
            List<String> urls=getAttachUrls(100, adminWorkerBO.getId().intValue());
            adminWorkerBO.setAttachInfo(urls);
        }
        replenish(adminWorkerBO);
        return adminWorkerBO;
    }

    private List<String> getAttachUrls(Integer bizType, Integer bizId) throws BusinessException {
        AttachQuery attachQuery=new AttachQuery();
        attachQuery.setBusinessType(bizType);
        attachQuery.setBusinessId(bizId);
        try{
            List<AttachDTO> params = attachApi.getAttachInfoByParam(attachQuery);
            List<String> urls=new ArrayList<>();
            if (!CollectionUtils.isEmpty(params)){
                for (AttachDTO param : params) {
                    urls.add("http://localhost:8092/static/"+param.getFileUuid());
                }
            }
            return urls;
        }catch (Exception e){
            throw new BusinessException(WorkerResultEnum.ATTACH_UPDATE_FAILED);
        }
    }
    @Autowired(required = false)
    private AccountApi accountApi;
    public Long auditSave(AuditSubmitParam param) throws BusinessException {
        //1. 使用参数中userId查询 当前workerBO
        AdminWorkerBO adminWorkerBO = workerRepository.getWorker(param.getWorkerId());
        if (adminWorkerBO ==null|| adminWorkerBO.getId()==null){
            //审核没有意义
            throw new BusinessException(WorkerResultEnum.WORKER_NOT_FOUND);
        }else{
            //2. 检查当前流转状态是否正确 2-0 2-1 0-1
            checkAuditStatus(param, adminWorkerBO);
            param.setUserId(param.getWorkerId());
            //3. audit新增日志 worker_audit_log
            Long auditId=workerAuditRepository.save(param);
            //4. 师傅审核状态更新 update worker set audit_status=#{} where user_id=
            WorkerParam workerParam=new WorkerParam();
            workerParam.setUserId(param.getWorkerId());
            workerParam.setAuditStatus(param.getAuditStatus());
            workerRepository.updateAuditStatus(workerParam);
            //5. 师傅表格记录了一个字段cert_status 0 没有账户 1 有账户 certification 认证 绑定业务意义是否有账户
            if (adminWorkerBO.getCertStatus()==0 && param.getAuditStatus()==1){
                AccountCreateParam accountCreateParam=new AccountCreateParam();
                accountCreateParam.setUserId(adminWorkerBO.getUserId());
                accountCreateParam.setUserPhone(adminWorkerBO.getPhone());
                accountCreateParam.setUserName(adminWorkerBO.getRealName());
                accountApi.createAccount(accountCreateParam);
                //师傅cert_status 从0 改成1
                workerParam.setCertStatus(1);//userId certStatus auditStatus
                workerRepository.updateCertStatus(workerParam);
            }
            return auditId;
        }
    }

    private void checkAuditStatus(AuditSubmitParam param, AdminWorkerBO bo) throws BusinessException {
        if (bo.getAuditStatus()==1){
            //审核状态流转失败
            throw new BusinessException(WorkerResultEnum.AUDIT_STATUS_TRANSFER_ERROR);
        }
    }

    public ListRecordTotalBO<AdminWorkerBO> queryWorker(WorkerListQuery query) {
        Long totalRecord = this.workerRepository.countWorker(query);
        List<AdminWorkerBO> adminWorkerBOS = null;
        if (totalRecord > 0) {
            adminWorkerBOS = this.workerRepository.queryWorkers(query);
            replenish(adminWorkerBOS);
        }
        return new ListRecordTotalBO<>(adminWorkerBOS, totalRecord);
    }

    public AdminWorkerBO getWorker(Long id) throws BusinessException {
        AdminWorkerBO worker = workerRepository.getWorker(id);
        if (worker != null) {
            try{
                //获取图片信息
                List<String> urls = getAttachUrls(100, worker.getId().intValue());
                worker.setAttachInfo(urls);
            }catch (Exception e){
                throw new BusinessException(WorkerResultEnum.ATTACH_FAILED);
            }
        }
        return worker;
    }

    public Integer enableWorker(Long workerId) {
        //师傅禁用 启用只影响抢单
        return workerRepository.enable(workerId);
    }

    public Integer disableWorker(Long workerId) {
        return workerRepository.disable(workerId);
    }
}
